<?php
/**
 * Created by IntelliJ IDEA.
 * User: wanglu
 * Date: 2017/7/19
 * Time: 14:13
 */

/**
 * Created by wanglu on 2017/7/19.
 */
class Content extends AdminBase
{

    function __construct()
    {
        parent::__construct();
        $this->load->service('user_service');
        $this->load->service('project_service');
        $this->load->service('lang_service');
        $this->load->service('key_service');
        $this->load->service('project_content_service');
        $this->load->service('project_version_service');
        $this->load->service('project_template_service');
    }

    /**
     * 历史数据
     */
    public function history_data() {
        $pvid  = $this->input->get("pvid");

        $project_version = $this->project_version_service->get_project_verson_by_id($pvid);
        $project = $this->project_service->get_project_by_id($project_version['pid']);
        $lang_version_info = json_decode($project_version['lang_version_info'], true);
        $project_user_relation = $this->project_service->get_project_user_relation($project['id'], $this->loginUser['id']);

        $columns = array();
        $columns[] = array(
            "field" => "key",
            "title" => "KEY",
            "width" => 200,
            "sortable" => true,
            "align" => "left"
        );


        $show_langs = array();

        foreach ($lang_version_info as $lvf) {
            if ($lvf['version'] != 0) {
                $show_langs[] = $lvf;
            }
        }

        $download_langs = array();
        foreach ($show_langs as $key => $sl) {
            $column = array();
            $column['width'] = 200;
            $column['align'] = 'left';
            $column['field'] = $sl['id'];

            $view_data = true;

            if ($project_user_relation['role'] != AppConstants::PROJECT_ROLE_INTERPRETER) {
                $view_data = true;
            } else {
                //是翻译员,查看是否有该语言查看数据权限
                $lang_user = $this->lang_service->get_lang_user($sl['id'], $this->loginUser['id']);
                if (empty($lang_user)) {
                    $view_data = false;
                }
            }

            if ($view_data) {
                $column['title'] = $sl['name'] . "_". $sl['shorthand'];
                $lang_hostory_contents = $this->project_version_service->get_lang_history_content($project['id'], $sl['id'], $sl['version']);
                $contents  = json_decode($lang_hostory_contents['content'], true);
                $show_langs[$key] ['key_content'] = $contents;
                $columns[] = $column;
                $download_langs[]= $sl;
            } else {
                $column['title'] = $sl['name'] . "-无查看权限";
                $show_langs[$key] ['key_content'] = array();
            }
        }

        $templates = $this->project_template_service->get_templates_by_pid($project['id']);

        $this->showView("project_content_history", array("columnsjson" => json_encode($columns), "project"=> $project, "columns"=> $columns, 'project_version'=> $project_version, 'templates'=>$templates, 'download_langs'=> $download_langs, 'project_user_relation'=> $project_user_relation ));
    }



    public function get_history_data() {
        $pvid  = $this->input->get("pvid");

        $project_version = $this->project_version_service->get_project_verson_by_id($pvid);
        $project = $this->project_service->get_project_by_id($project_version['pid']);

        $pkeys = json_decode($project_version['pkey_info'], true);
        $lang_version_info = json_decode($project_version['lang_version_info'], true);

        $project_user_relation = $this->project_service->get_project_user_relation($project['id'], $this->loginUser['id']);



        $show_langs = array();

        foreach ($lang_version_info as $lvf) {
            if ($lvf['version'] != 0) {
                $show_langs[] = $lvf;
            }
        }

        foreach ($show_langs as $key => $sl) {
            $view_data = true;
            if ($project_user_relation['role'] != AppConstants::PROJECT_ROLE_INTERPRETER) {
                $view_data = true;
            } else {
                //是翻译员,查看是否有该语言查看数据权限
                $lang_user = $this->lang_service->get_lang_user($sl['id'], $this->loginUser['id']);
                if (empty($lang_user)) {
                    $view_data = false;
                }
            }

            if ($view_data) {
                $lang_hostory_contents = $this->project_version_service->get_lang_history_content($project['id'], $sl['id'], $sl['version']);
                $contents  = json_decode($lang_hostory_contents['content'], true);
                $show_langs[$key] ['key_content'] = $contents;

            } else {
                $show_langs[$key] ['key_content'] = array();
            }
        }

        $datas = array();
        foreach ($pkeys as $pkey) {
            $data = array(
                'key' => $pkey['pkey'],
            );


            foreach ($show_langs as   $lang) {
                $langContents = $lang['key_content'];

                if (empty($langContents[$pkey['pkey']])) {
                    $data[$lang['id']] = '';
                } else {
                    $data[$lang['id']] = $langContents[$pkey['pkey']]['content'];
                }
            }
            $datas[] = $data;
        }
        echo json_encode($datas);
    }



    public function data()
    {
        $pid = $this->input->get("pid");
        $project = $this->project_service->get_project_by_id($pid);
        $project_user_relation = $this->project_service->get_project_user_relation($pid, $this->loginUser['id']);

        //当前用户是创建者或者 管理员关系
        if ($project_user_relation['role'] == AppConstants::PROJECT_ROLE_OWNER ||
            $project_user_relation['role'] == AppConstants::PROJECT_ROLE_ADMIN) {
            $langs = $this->lang_service->get_langs_by_pid($pid);
            foreach ($langs as $key => $value) {
                $langs[$key]['permission'] = AppConstants::LANG_LANG_PERMISSION_READ_WRITE;
                $langs[$key]['lang_id'] = $langs[$key]['id'];
            }
        }

        //翻译员
        if ($project_user_relation['role'] == AppConstants::PROJECT_ROLE_INTERPRETER) {
            $langs = $this->project_service->get_user_langs($pid, $this->loginUser['id']);
        }


        $columns = array();
        $columns[] = array(
            "field" => "key",
            "title" => "KEY",
            "width" => 200,
            "sortable" => true,
            "align" => "left"
        );

        foreach ($langs as $key => $lang) {

            $column = array();
            $column['width'] = 200;
            $column['align'] = 'left';
            $column['permission'] = $lang['permission'];

            if ($lang['permission'] == AppConstants::LANG_LANG_PERMISSION_READ_WRITE) {
                $title = $lang['name'] . "_" . $lang['shorthand'] . "(读写)";
                $column['editor'] = 'textarea';

            }

            if ($lang['permission'] == AppConstants::LANG_PERMISSION_READ_ONLY) {
                $title = $lang['name'] . "_" . $lang['shorthand'] . "(只读)";
            }


            $column['title'] = $title;
            $column['field'] = $lang['id'];
            $columns[] = $column;
            $langContents = $this->project_content_service->get_project_content($pid, $lang['id']);

            $lang_key_content = array();
            foreach ($langContents as $lc) {
                $lang_key_content[$lc['pkey']] = $lc['content'];

            }

            $langs[$key] ['key_content'] = $lang_key_content;
        }

        $templates = $this->project_template_service->get_templates_by_pid($pid);
        $this->showView("project_interpreter2", array("columnsjson" => json_encode($columns), "project"=> $project, "columns"=> $columns, 'langs'=> $langs, 'templates'=> $templates, "project_user_relation"=> $project_user_relation));
    }


   public function get_edit_data() {
       $pid = $this->input->get("pid");
       $project_user_relation = $this->project_service->get_project_user_relation($pid, $this->loginUser['id']);

       //当前用户是创建者或者 管理员关系
       if ($project_user_relation['role'] == AppConstants::PROJECT_ROLE_OWNER ||
           $project_user_relation['role'] == AppConstants::PROJECT_ROLE_ADMIN) {
           $langs = $this->lang_service->get_langs_by_pid($pid);

           foreach ($langs as $key => $value) {
               $langs[$key]['permission'] = AppConstants::LANG_LANG_PERMISSION_READ_WRITE;
               $langs[$key]['lang_id'] = $langs[$key]['id'];
           }
       }

       //翻译员
       if ($project_user_relation['role'] == AppConstants::PROJECT_ROLE_INTERPRETER) {
           $langs = $this->project_service->get_user_langs($pid, $this->loginUser['id']);
       }

       $pkeys = $this->project_service->get_project_keys($pid);

       $columns = array();
       $columns[] = array(
           "field" => "key",
           "title" => "KEY",
           "width" => 200,
           "sortable" => true,
           "align" => "left"
       );


       foreach ($langs as $key => $lang) {

           $column = array();
           $column['width'] = 200;
           $column['align'] = 'left';
           $column['permission'] = $lang['permission'];

           if ($lang['permission'] == AppConstants::LANG_LANG_PERMISSION_READ_WRITE) {
               $title = $lang['name'] . "_" . $lang['shorthand'] . "(读写)";
               $column['editor'] = 'textarea';

           }

           if ($lang['permission'] == AppConstants::LANG_PERMISSION_READ_ONLY) {
               $title = $lang['name'] . "_" . $lang['shorthand'] . "(只读)";
           }


           $column['title'] = $title;
           $column['field'] = $lang['id'];
           $columns[] = $column;
           $langContents = $this->project_content_service->get_project_content($pid, $lang['id']);



           $lang_key_content = array();
           foreach ($langContents as $lc) {
               $lang_key_content[$lc['pkey']] = $lc['content'];

           }

           $langs[$key] ['key_content'] = $lang_key_content;
       }


       $datas = array();

       foreach ($pkeys as $pkey) {

           $data = array(
               'key' => $pkey['pkey'],
           );

           foreach ($langs as   $lang) {
               $langContents = $lang['key_content'];
               if (empty($langContents[$pkey['pkey']])) {
                   $data[$lang['id']] = '';
               } else {
                   $data[$lang['id']] = $langContents[$pkey['pkey']];
               }
           }
           $datas[] = $data;
       }

        echo json_encode($datas);
   }

    /**
     * 编辑提交
     */
    public function submitcontent() {
        $rowData = $this->input->post("row");
        $pid = $this->input->post("pid");
        $rowData = json_decode($rowData, true);
        $pkey = $rowData['key'];


        foreach ($rowData as $key => $value) {
            if ($key != 'key') {
                //保存货修改内容
                $res = $this->project_content_service->save_or_update_temp_content($pkey, $pid, $key, $value);
                if (!$res) {
                    //die(json_encode(array("code" => 201, "msg"=> '保存出错')));
                  //  break;
                }
            }
        }
        die(json_encode(array("code" => 200)));
    }

    /**
     * 导入
     */
    public function inport_data() {
        $this->parseSoldExcel("slife_strings2.csv");
    }


    const  SOLD_EXCEL_PATH = "upload/i18n/";
    public function parseSoldExcel($filename)
    {
        require_once APPPATH . 'libraries/PHPExcel/Classes/PHPExcel/IOFactory.php';

        $pid = 14;
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);

        define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

        date_default_timezone_set('Europe/London');

        /** Include PHPExcel_IOFactory */
        $excelFile = APPPATH . self::SOLD_EXCEL_PATH . $filename;

        if (!file_exists($excelFile)) {
            exit($filename . " is not exits");
        }

        $objPHPExcel = PHPExcel_IOFactory::load($excelFile);

        $objWorksheet = $objPHPExcel->getSheet(0);

        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();

        $arr = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J',
            11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T',
            21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');

        $lang_ids = array();


        //第二列开始是
        for ($column = 2; $arr[$column] != $highestColumn; $column++) {
            $shorthand = $objWorksheet->getCellByColumnAndRow($column, 1)->getValue();
            if (!empty($shorthand)) {
                $lang_id = $this->lang_service->add_lang_return_id($pid, $shorthand, $shorthand, $shorthand);
                $lang_ids[$column] = $lang_id;
            }
        }



        $contents  = array();
        for ($row = 2; $row <= $highestRow; $row++) {
            $pkey = $objWorksheet->getCellByColumnAndRow(0, $row)->getValue();
            //跳过注释
            if (strpos($pkey, "#")  === false &&  !empty($pkey)) {
                //添加  KEY
                $this->key_service->import_add_key($pid, $pkey, $row-2);

                for ($column = 2; $arr[$column] != $highestColumn; $column++) {
                    $value = $objWorksheet->getCellByColumnAndRow($column, $row)->getValue();
                    if (empty($value)) {
                        $value = '';
                    }

                    $content_data = array(
                        'pid'=> $pid,
                        'lang_id'=> $lang_ids[$column],
                        'pkey'=> $pkey,
                        'content'=> $value,
                        'updatetime'=> time(),
                        'createtime'=> time()
                    );

                    $contents[] = $content_data;
                }
            }
        }


        $this->project_content_service->batch_insert_temp_contents($contents);



        //echo json_encode($contents);


        return true;
    }


    const  DOWNLOAD_PATH = "download/i18n_release/";

    public function export_template() {

        $this->load->library('zip');
        $this->load->library('parser');

        $lang_ids  = $this->input->get("lang_ids");
        $lang_ids = json_decode($lang_ids, true);
        $tpl_id  = $this->input->get("tpl_id");
        $template = $this->project_template_service->get_template_by_id($tpl_id);
        $pid = $this->input->get("pid");


        $download_path = APPPATH . self::DOWNLOAD_PATH ;
        $langs = $this->lang_service->get_langs_by_pid($pid);
        $download_langs = array();
        foreach ($langs as $lang) {
            foreach ($lang_ids as  $lang_id) {
                if ($lang['id'] == $lang_id) {
                    $download_langs[] = $lang;
                }
            }
        }


        foreach ($download_langs as $key => $lang) {
            $langContents = $this->project_content_service->get_project_content($pid, $lang['id']);
            $lang_key_content = array();

            foreach ($langContents as $lc) {
                $lang_key_content[$lc['pkey']] = $lc['content'];

            }
            $download_langs[$key] ['key_content'] = $lang_key_content;
        }

        $pkeys = $this->project_service->get_project_keys($pid);


        $tplname = strtolower($template['name']);



        foreach ($download_langs as $lang) {

            $langContents = $lang['key_content'];
            $contetn_datas =  array();
            foreach ($pkeys as $pkey) {
                if (!empty($langContents[$pkey['pkey']])) {
                    $content = $langContents[$pkey['pkey']];
                } else {
                    $content = '';
                }
                $content = str_replace('"', '\"', $content);
                $content = str_replace("\'", "'", $content);

                $content = str_replace("'", "\'", $content);
                //$content = addslashes($content);
                //$content = str_replace('\\n', '\n', $content);

                /**
                 *  %s, %1$s     %@, %1$@     %s, %1$s
                 */


                if (strpos($tplname, 'ios') === false) {
                   // $content = str_replace("&", '&amp', $content);
                } else {
                    $content = str_replace('%s', '%@', $content);
                    $content = str_replace('$s', '$@', $content);
                }

                $contetn_datas[] = array(
                    'key'=> $pkey['pkey'],
                    'value'=> $content
                );
            }


            $file_name = str_replace( "#s", $lang['shorthand'], $template['filename']);
            $folder = $this->get_tpl_foler($lang, $template);

            $outputData  = $this->parser->parse_string($template['template'],  array('datas' => $contetn_datas));

            $this->zip->add_data($folder."/". $file_name, $outputData);

            //IOS 模板  base 处理
            if (strpos($tplname, 'ios') !== false && strtolower($lang['shorthand']) == 'en' ) {
                $this->zip->add_data("Base.lproj/". $file_name, $outputData);
            }
        }




        $this->zip->archive($download_path. '/i18n_release.zip');
        $this->zip->download('i18n_release.zip');
    }


    public function export_history_template() {

        $this->load->library('zip');
        $this->load->library('parser');

        $lang_ids  = $this->input->get("lang_ids");
        $lang_ids = json_decode($lang_ids, true);
        $tpl_id  = $this->input->get("tpl_id");
        $template = $this->project_template_service->get_template_by_id($tpl_id);

        $pvid = $this->input->get("pvid");

        $project_version = $this->project_version_service->get_project_verson_by_id($pvid);
        $lang_version_info = json_decode($project_version['lang_version_info'], true);
        $project = $this->project_service->get_project_by_id($project_version['pid']);
        $pkeys = json_decode($project_version['pkey_info'], true);

        $download_path = APPPATH . self::DOWNLOAD_PATH ;
        $download_langs = array();
        foreach ($lang_version_info as $lang) {
            foreach ($lang_ids as  $lang_id) {
                if ($lang['id'] == $lang_id) {
                    $download_langs[] = $lang;
                }
            }
        }

        foreach ($download_langs as $key => $lang) {
            $lang_hostory_contents = $this->project_version_service->get_lang_history_content($project['id'], $lang['id'], $lang['version']);
            $contents  = json_decode($lang_hostory_contents['content'], true);
            $download_langs[$key]['key_content'] = $contents;
        }

        foreach ($download_langs as $lang) {

            $langContents = $lang['key_content'];
            $contetn_datas =  array();
            foreach ($pkeys as $pkey) {

                if (!empty($langContents[$pkey['pkey']]['content'])) {
                    $content = $langContents[$pkey['pkey']]['content'];
                } else {
                    $content = '';
                }

                $contetn_datas[] = array(
                    'key'=> $pkey['pkey'],
                    'value'=> $content
                );
            }

            $file_name = str_replace( "#s", $lang['shorthand'], $template['filename']);
            $folder = $this->get_tpl_foler($lang, $template);

            $outputData  = $this->parser->parse_string($template['template'],  array('datas' => $contetn_datas));

            $this->zip->add_data($folder."/". $file_name, $outputData);
        }

        $this->zip->archive($download_path. '/i18n_release.zip');
        $this->zip->download('i18n_release.zip');
    }

    private function get_tpl_foler($lang, $template) {

        $export_folder = $lang['shorthand'];

        $folders = json_decode($template['folder'], true);

        foreach ($folders as $folder) {
            if ($folder['shorthand'] == $lang['shorthand']) {

                $export_folder = $folder['folder'];
                break;
            }
        }

        return $export_folder;
    }

}